package com.oa.servlet;

import com.oa.entity.Employee;
import com.oa.service.EmployeeService;
import com.oa.service.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、获取用户请求的数据
		String opr = request.getParameter("opr"); //请求的操作类型
		if(opr==null){
			opr = "login";//默认登入
		}
		switch (opr){
			case "login":
				login(request, response);
				break;
			case "logout":
				logout(request, response);
				break;
		}

	}

	//登入
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、获取用户请求的数据
		String employeeNo = request.getParameter("employeeNo");
		String password = request.getParameter("password");
		//2、操作
		EmployeeService service = new EmployeeServiceImpl();
		Employee loginEmp = service.findByParam(employeeNo,password);
		//3、页面跳转==》判断是否需要传递数据==》转发 / 重定向
		request.getSession().setAttribute("loginEmp",loginEmp);
		response.sendRedirect("index.jsp");
	}

	//退出
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//
		request.getSession().removeAttribute("loginEmp");
		response.sendRedirect("login.jsp");
	}
}
